﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using V5_PhoneLibs.Core;
using System.Text;
using System.IO.IsolatedStorage;
using System.IO;
using System.Windows.Resources;
using V5_Book.Model;
using Coding4Fun.Toolkit.Controls;
using System.Windows.Media.Imaging;

namespace V5_Book.View {
    public partial class BookView1 : PhoneApplicationPage {

        private int currentIndex = 1;
        private int BookCount = 0;
        private IsolatedStorageFileStream fileStream;
        private List<ModelBookInfo> listBookInfo = new List<ModelBookInfo>();
        private ModelBookInfo m_BookInfo = new ModelBookInfo();
        private Dictionary<int, string> BookList = new Dictionary<int, string>();

        public BookView1() {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(BookView1_Loaded);
            this.BookView.MouseEnter += new MouseEventHandler(BookView_MouseEnter);
            this.BookButtomSetting.MouseEnter += new MouseEventHandler(BookButtomSetting_MouseEnter);
        }

        void BookButtomSetting_MouseEnter(object sender, MouseEventArgs e) {
            UrlHelper.Instance.Action(this, "/View/BookViewSettings.xaml");
        }

        void BookView1_Loaded(object sender, RoutedEventArgs e) {
            var bookName = this.NavigationContext.QueryString["bookname"];
            listBookInfo = BookHelper.Instance.ListBookInfo();
            m_BookInfo = listBookInfo.FirstOrDefault(p => p.BookName == bookName);
            this.Read_Text(bookName);
            currentIndex = m_BookInfo.BookIndex;
            this.BookTop1.Text = m_BookInfo.BookName;
            this.BookTop2.Text = DateTime.Now.ToString("HH:mm");
            this.BookView.Text = BookList.FirstOrDefault(p => p.Key == currentIndex).Value;
        }

        void BookView_MouseEnter(object sender, MouseEventArgs e) {
            SlideTransitionMode mod = SlideTransitionMode.SlideLeftFadeIn;
            var pos = e.GetPosition(this.BookView);
            if (pos.X > 240) {
                currentIndex++;
                if (currentIndex >= BookList.Count) {
                    return;
                }
                m_BookInfo.BookIndex = currentIndex;
                m_BookInfo.LastTime = DateTime.Now;
            }
            else {
                mod = SlideTransitionMode.SlideRightFadeIn;
                currentIndex--;
                if (currentIndex < 1) {
                    return;
                }
                m_BookInfo.BookIndex = currentIndex;
                m_BookInfo.LastTime = DateTime.Now;
            }

            TransitionElement transitionElement = new SlideTransition { Mode = mod };
            //PhoneApplicationPage phoneApplicationPage = (PhoneApplicationPage)(((PhoneApplicationFrame)Application.Current.RootVisual)).Content;
            ITransition transition = transitionElement.GetTransition(this.BookView);
            transition.Completed += delegate {
                transition.Stop();
            };
            transition.Begin();


            BookHelper.Instance.SaveListBookInfo(listBookInfo, m_BookInfo);
            this.BookView.Text = BookList.Single(p => p.Key == currentIndex).Value;
            //计算总索引
            //double currentPercent123 = Math.IEEERemainder(currentIndex, BookCount) % 1000;
            this.BookButtomPercent.Text = currentIndex.ToString();// currentPercent123.ToString() + "%";
            this.BookTop2.Text = DateTime.Now.ToString("HH:mm");
        }

        private void Read_Text(string bookName) {

            #region 打开独立存储区的内容
            if (!FsoHelper.Instance.IsFileExists(bookName + ".txt")) {
                MessageBox.Show(bookName + ",该书籍不存在!");
                UrlHelper.Instance.Action(this, "/MainPage.xaml");
                return;
            }
            string str = FsoHelper.Instance.Read(bookName + ".txt");
            str = str.Replace("!!", "\r").Replace("$$", "\n");
            #endregion

            this.BookView.LineHeight = 40;
            this.BookView.FontSize = 30;
            var b = new ImageBrush();
            b.ImageSource = new BitmapImage(
                    new Uri(@"\Images\BK\b6n.png", UriKind.RelativeOrAbsolute)
                );
            ;
            this.borderBG.Background = b;
            double fontHeight = GetTextBlockHeight(this.BookView, '中');//GetPageLine(this.BookView, '中')
            double fontWidth = GetTextBlockWidth(this.BookView, '中');

            int columnCount = (Int32)(AppHelper.Instance.ScreenWidth / fontWidth);
            int rowCount = this.GetPageLine(this.BookView, '中', 680);

            string[] bookRowList = str.Split(new string[] { "\r" }, StringSplitOptions.None);
            BookCount = bookRowList.Length;
            int rowLoopCount = 1;
            int bookIndex = 0;
            StringBuilder sb = new StringBuilder();
            foreach (string row in bookRowList) {
                string tempRowOut = " " + row;
                if (tempRowOut.Length > columnCount) {
                    //该行显示多少行
                    int tempRow = tempRowOut.Length / columnCount;
                    for (int i = 0; i < tempRow; i++) {
                        rowLoopCount++;
                        string s = string.Empty;
                        if (i + 1 == tempRow) {
                            sb.Append(tempRowOut.Substring(i * columnCount));
                            //sb.Append("\r");
                        }
                        else {
                            s = tempRowOut.Substring(i * columnCount, columnCount);
                            sb.Append(s);
                        }
                        if (rowLoopCount == rowCount) {
                            bookIndex++;
                            BookList.Add(bookIndex, sb.ToString());
                            rowLoopCount = 1;
                            sb = new StringBuilder();
                        }
                    }
                }
                else {
                    rowLoopCount++;
                    sb.Append(tempRowOut);
                    if (string.IsNullOrEmpty(tempRowOut)) {
                        sb.Append("\r");
                    }
                    if (rowLoopCount == rowCount) {
                        bookIndex++;
                        BookList.Add(bookIndex, sb.ToString());
                        rowLoopCount = 1;
                        sb = new StringBuilder();
                    }
                }
            }
            this.BookView.Text = BookList.FirstOrDefault(p => p.Key == currentIndex).Value;
        }

        //获取文本框线
        private int GetPageLine(TextBlock tb, char c, double controlHeight) {
            double textBlockHeight = this.GetTextBlockHeight(tb, c);
            if (textBlockHeight > 0.0) {
                return (int)(controlHeight / textBlockHeight);
            }
            return 0;
        }
        //获取字符高度
        private double GetTextBlockHeight(TextBlock tb, char c) {
            tb.Text = c.ToString();
            return tb.ActualHeight;
        }
        //获取字符宽度
        private double GetTextBlockWidth(TextBlock tb, char c) {
            tb.Text = c.ToString();
            return tb.ActualWidth;
        }

        private void BookButtomPercent_Click(object sender, RoutedEventArgs e) {
            InputPrompt prompt = new InputPrompt();
            prompt.Completed += new EventHandler<PopUpEventArgs<string, PopUpResult>>(prompt_Completed);
            prompt.Title = "快速移动";
            prompt.Message = "请输入移动到%（如：10.23）";
            InputScope scope = new InputScope();
            InputScopeName name = new InputScopeName();
            name.NameValue = InputScopeNameValue.Text;
            scope.Names.Add(name);
            prompt.InputScope = scope;
            prompt.Show();
        }

        private void prompt_Completed(object sender, PopUpEventArgs<string, PopUpResult> e) {
            string result = e.Result;
            if (e.PopUpResult == PopUpResult.Ok) {
                string s = result;
                s = s.Replace("%", "");
                try {
                    double num = double.Parse(s) / 100.0;
                    if ((num <= 1.0) && (num >= 0.0)) {
                        //double num2 = this.bookFactory.fileSize * num;
                        //Debug.WriteLine("input_Completed========={0},{1}", new object[] { num, num2 });
                        //this.bookFactory.startPos = (int)num2;
                        //this.bookFactory.endPos = this.bookFactory.startPos + 0xfa0L;
                        //this.DrawCurrPage();
                    }
                }
                catch (Exception) {
                }
            }
        }
    }
}